package com.study.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Set;

public class SecondRealm extends AuthorizingRealm {

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入SecondRealm:["+authenticationToken+"]");
//        强行转换为login传入的Token类型
//        里面保存了前台输入的用户名密码
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
//        与数据库交互获取
//        认证的实体信息
        Object Username="admin";
        ByteSource byteSource=ByteSource.Util.bytes(Username);
//        密码
        String pwd="49d9fbf007fd95343492e607aa34455eeb062b26";
//        进行比较
        AuthenticationInfo info = new SimpleAuthenticationInfo(Username, pwd, byteSource, getName());
        return info;
    }

    public static void main(String[] args) {
        SimpleHash simple=new SimpleHash("SHA1","123","admin",1024);
        System.out.println(simple);
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Object primaryPrincipal=principalCollection.getPrimaryPrincipal();
        Set<String> roles=new HashSet<>();
        roles.add("user");
        if("admin".equals(primaryPrincipal)){
            roles.add("admin");
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(roles);
        return info;
    }
}
